const { setCookie, getCookie } = require('../src/lib/cookie-store');
const validateInput = require('../src/lib/inputValidator');
const { launch, get_user_details } = require('../src/lib/puppeteer-client');
const { findAll } = require('../src/lib/users-store');

function validate(input) {
    // 添加你的验证逻辑
    return input.trim() !== '';
}
function validateNumber(input) {
    // 添加你的验证逻辑
    return !isNaN(input);
}
const extractUrls = (text) => {
    // 正则表达式用于匹配URL
    const urlRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;
    // 使用match方法提取URL
    const urls = text.match(urlRegex);
    return urls || [];  // 如果没有匹配项，返回空数组
};

(async () => {
    let storeCookie = await getCookie('douyin');
    // console.log(storeCookie);
    if (storeCookie) {
    } else {
        const inputCookie = await validateInput(validate, '请输入cookie：');
        await setCookie('douyin', inputCookie);
        storeCookie = inputCookie;
    }
    const min = await validateInput(validateNumber, '请输入监控频率（分）：\n');
    start(storeCookie);
    setInterval(async () => {
        start(storeCookie);

    }, min * 60 * 1000);

})();

async function start(storeCookie) {
    const users = await findAll();
    for (let i = 0; i < users.length; i++) {
        console.log(users[i].nickname + ' 处理中');
        launch(['https://www.douyin.com/user/' + users[i].secUid], storeCookie, '.douyin.com', {
            aweme_list: function (data) {
                diffAwemeList(data);
            }
        });
    }
}
function diffAwemeList(awemeList) {
    for (let j = 0; j < awemeList.length; j++) {
        let result = {};
        result['aweme_id'] = awemeList[j].aweme_id;
        result['desc'] = awemeList[j].desc;
        result['create_time'] = awemeList[j].create_time;
        result['nickname'] = awemeList[j].author.nickname;
        result['sec_uid'] = awemeList[j].author.sec_uid;
        result['uid'] = awemeList[j].author.uid;
        result['aweme_count'] = awemeList[j].author.aweme_count;
        result['following_count'] = awemeList[j].author.following_count;
        result['follower_count'] = awemeList[j].author.follower_count;
        result['favoriting_count'] = awemeList[j].author.favoriting_count;
        result['total_favorited'] = awemeList[j].author.total_favorited;

        result['paly_url'] = awemeList[j].video.play_addr.url_list[0];
        // result['videp'] = awemeList[j].video;
        console.log(result);
    }
}


